package concurrent.aqs;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program JavaBase
 * @description: 锁-条件变量的支持
 * @author: zhanglu
 * @create: 2021-05-22 14:48:00
 */
@Slf4j
public class LockCondition {

    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    @Test
    public void test01() throws InterruptedException {
        new Thread(() -> {
            lock.lock();
            try {
                log.info("begin wait");
                condition.await();
                log.info("end wait");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(() -> {
            lock.lock();
            try {
                log.info("begin signal");
                condition.signal();
                log.info("end signal");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();
        Thread.currentThread().join();
    }

    @Test
    public void test02(){
        lock.lock();
        try {
            log.info("begin lock");
            lock.lock();
            log.info("end lock");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
